/**
 * @version 2007-5-22
 * @author xalinx at gmail dot com
 */
package org.nanhill.vest.export;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nanhill.vest.component.Builder;
import org.nanhill.vest.component.Component;
import org.nanhill.vest.component.DefaultBuilder;
import org.nanhill.vest.component.Dynamic;

/**
 * @version 2007-5-22
 * @author xalinx at gmail dot com
 * 
 */
public class DefaultModelExporter implements ModelExporter {
	private Map<Integer, Builder> templates = new HashMap<Integer, Builder>();

	public void export(Component comp, Writer writer) {
		Builder builder = templates.get(comp.hashCode());
		if (null == builder) {
			builder = new DefaultBuilder();
			comp.build(builder);
			builder.shrink();
			templates.put(comp.hashCode(), builder);
		}
		export(builder, writer);
	}

	public void export(Builder builder, Writer writer) {
		List<Object> buffers = builder.getBuffers();
		for (int i = 0; i < buffers.size(); i++) {
			Object obj = buffers.get(i);
			if (obj instanceof String) {
				try {
					writer.write((String) obj);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else if (obj instanceof Dynamic) {
				Dynamic dy = (Dynamic) obj;
				// TODO performance
				Builder tmp = new DefaultBuilder();
				dy.exe(tmp);
				export(tmp, writer);
			}
		}
	}
}
